import AsyncStorage from '@react-native-async-storage/async-storage';

// 好友请求状态类型
type FriendRequestStatus = 'pending' | 'accepted' | 'rejected';

// 聊天消息状态类型
type MessageStatus = 'sent' | 'delivered' | 'read';

// 好友接口
export interface Friend {
  _id: string;
  username: string;
  avatar: string;
  uid: string;
  lastMessage?: ChatMessage;
  unreadCount: number;
  lastOnline: string;
}

// 好友请求接口
interface FriendRequest {
  requestId: string;
  senderId: string;
  receiverId: string;
  content: string;
  timestamp: number;
  status: FriendRequestStatus;
}

// 聊天消息接口
interface ChatMessage {
  id: string;
  senderId: string;
  receiverId: string;
  content: string;
  timestamp: number;
  status: MessageStatus;
}

// 存储键名常量
const STORAGE_KEYS = {
  FRIEND_REQUESTS: 'friendRequests',
  CHAT_MESSAGES: 'chatMessages',
};

// 消息存储服务
export const MessageStorage = {
  // 添加好友请求
  async addFriendRequest(request: FriendRequest) {
    try {
      const existingRequests = await this.getFriendRequests();
      // 检查是否已存在相同的请求
      const isDuplicate = existingRequests.some(
        (req) => req.senderId === request.senderId && req.status === 'pending'
      );
      if (isDuplicate) {
        return false;
      }
      
      const updatedRequests = [...existingRequests, {
        ...request,
        timestamp: Date.now(),
        status: 'pending'
      }];
      
      await AsyncStorage.setItem(
        STORAGE_KEYS.FRIEND_REQUESTS,
        JSON.stringify(updatedRequests)
      );
      
      return true;
    } catch (error) {
      console.error('存储好友请求失败:', error);
      return false;
    }
  },

  // 获取所有好友请求
  async getFriendRequests(): Promise<FriendRequest[]> {
    try {
      const requests = await AsyncStorage.getItem(STORAGE_KEYS.FRIEND_REQUESTS);
      return requests ? JSON.parse(requests) : [];
    } catch (error) {
      console.error('获取好友请求失败:', error);
      return [];
    }
  },

  // 更新好友请求状态
  async updateFriendRequest(updatedRequest: FriendRequest) {
    try {
      const requests = await this.getFriendRequests();
      const updatedRequests = requests.map((request) =>
        request.requestId === updatedRequest.requestId 
          ? { ...request, ...updatedRequest, timestamp: Date.now() }
          : request
      );
      
      await AsyncStorage.setItem(
        STORAGE_KEYS.FRIEND_REQUESTS,
        JSON.stringify(updatedRequests)
      );
      return true;
    } catch (error) {
      console.error('更新好友请求失败:', error);
      return false;
    }
  },

  // 添加聊天消息
  async addMessage(message: ChatMessage) {
    try {
      const chatKey = this.getChatKey(message.senderId, message.receiverId);
      const existingMessages = await this.getMessages(message.senderId, message.receiverId);
      
      const updatedMessages = [...existingMessages, {
        ...message,
        timestamp: Date.now(),
        status: 'sent'
      }];
      
      await AsyncStorage.setItem(
        chatKey,
        JSON.stringify(updatedMessages)
      );
      return true;
    } catch (error) {
      console.error('存储聊天消息失败:', error);
      return false;
    }
  },

  // 获取指定聊天的消息
  async getMessages(userId1: string, userId2: string): Promise<ChatMessage[]> {
    try {
      const chatKey = this.getChatKey(userId1, userId2);
      const messages = await AsyncStorage.getItem(chatKey);
      return messages ? JSON.parse(messages) : [];
    } catch (error) {
      console.error('获取聊天消息失败:', error);
      return [];
    }
  },

  // 生成聊天存储键
  getChatKey(userId1: string, userId2: string): string {
    // 确保聊天key的一致性，将两个ID按字母顺序排序
    const sortedIds = [userId1, userId2].sort();
    return `chat_${sortedIds[0]}_${sortedIds[1]}`;
  },

  // 更新消息状态
  async updateMessageStatus(messageId: string, status: MessageStatus, senderId: string, receiverId: string) {
    try {
      const messages = await this.getMessages(senderId, receiverId);
      const updatedMessages = messages.map((msg) =>
        msg.id === messageId ? { ...msg, status } : msg
      );
      
      const chatKey = this.getChatKey(senderId, receiverId);
      await AsyncStorage.setItem(
        chatKey,
        JSON.stringify(updatedMessages)
      );
      return true;
    } catch (error) {
      console.error('更新消息状态失败:', error);
      return false;
    }
  }
};